import time
import threading
from typing import Dict, List
from collections import deque
import logging

class PerformanceMonitor:
    """
    性能监控器
    监控tick处理性能，帮助识别性能瓶颈
    """
    
    def __init__(self, max_samples=1000):
        self.max_samples = max_samples
        
        # 性能指标
        self.tick_processing_times = deque(maxlen=max_samples)
        self.tick_timestamps = deque(maxlen=max_samples)
        self.queue_sizes = deque(maxlen=max_samples)
        self.cache_hit_rates = deque(maxlen=max_samples)
        
        # 统计信息
        self.total_ticks = 0
        self.total_processing_time = 0
        self.max_processing_time = 0
        self.min_processing_time = float('inf')
        
        # 监控线程
        self.monitoring = False
        self.monitor_thread = None
        
    def start_monitoring(self, interval=60):
        """启动性能监控"""
        self.monitoring = True
        self.monitor_thread = threading.Thread(
            target=self._monitor_worker, 
            args=(interval,), 
            daemon=True
        )
        self.monitor_thread.start()
        logging.info("性能监控已启动")
        
    def stop_monitoring(self):
        """停止性能监控"""
        self.monitoring = False
        if self.monitor_thread:
            self.monitor_thread.join(timeout=1)
        logging.info("性能监控已停止")
        
    def _monitor_worker(self, interval):
        """监控工作线程"""
        while self.monitoring:
            try:
                self._log_performance_stats()
                time.sleep(interval)
            except Exception as e:
                logging.error(f"性能监控异常: {e}")
                
    def record_tick_processing(self, processing_time: float):
        """记录tick处理时间"""
        self.tick_processing_times.append(processing_time)
        self.tick_timestamps.append(time.time())
        
        # 更新统计信息
        self.total_ticks += 1
        self.total_processing_time += processing_time
        self.max_processing_time = max(self.max_processing_time, processing_time)
        self.min_processing_time = min(self.min_processing_time, processing_time)
        
    def record_queue_size(self, queue_size: int):
        """记录队列大小"""
        self.queue_sizes.append(queue_size)
        
    def record_cache_hit_rate(self, hit_rate: float):
        """记录缓存命中率"""
        self.cache_hit_rates.append(hit_rate)
        
    def get_processing_stats(self) -> Dict[str, float]:
        """获取处理性能统计"""
        if not self.tick_processing_times:
            return {
                "avg_processing_time": 0,
                "max_processing_time": 0,
                "min_processing_time": 0,
                "total_ticks": 0,
                "ticks_per_second": 0
            }
            
        recent_times = list(self.tick_processing_times)
        avg_time = sum(recent_times) / len(recent_times)
        
        # 计算每秒处理tick数
        if len(self.tick_timestamps) > 1:
            time_span = self.tick_timestamps[-1] - self.tick_timestamps[0]
            ticks_per_second = len(recent_times) / time_span if time_span > 0 else 0
        else:
            ticks_per_second = 0
            
        return {
            "avg_processing_time": avg_time,
            "max_processing_time": self.max_processing_time,
            "min_processing_time": self.min_processing_time if self.min_processing_time != float('inf') else 0,
            "total_ticks": self.total_ticks,
            "ticks_per_second": ticks_per_second
        }
        
    def get_queue_stats(self) -> Dict[str, float]:
        """获取队列统计"""
        if not self.queue_sizes:
            return {"avg_queue_size": 0, "max_queue_size": 0}
            
        recent_sizes = list(self.queue_sizes)
        return {
            "avg_queue_size": sum(recent_sizes) / len(recent_sizes),
            "max_queue_size": max(recent_sizes)
        }
        
    def get_cache_stats(self) -> Dict[str, float]:
        """获取缓存统计"""
        if not self.cache_hit_rates:
            return {"avg_hit_rate": 0}
            
        recent_rates = list(self.cache_hit_rates)
        return {
            "avg_hit_rate": sum(recent_rates) / len(recent_rates)
        }
        
    def _log_performance_stats(self):
        """记录性能统计日志"""
        processing_stats = self.get_processing_stats()
        queue_stats = self.get_queue_stats()
        cache_stats = self.get_cache_stats()
        
        logging.info(f"性能统计 - "
                    f"平均处理时间: {processing_stats['avg_processing_time']:.4f}s, "
                    f"最大处理时间: {processing_stats['max_processing_time']:.4f}s, "
                    f"每秒处理tick数: {processing_stats['ticks_per_second']:.1f}, "
                    f"平均队列大小: {queue_stats['avg_queue_size']:.1f}, "
                    f"平均缓存命中率: {cache_stats['avg_hit_rate']:.1f}%")
        
    def get_comprehensive_stats(self) -> Dict[str, any]:
        """获取综合性能统计"""
        return {
            "processing": self.get_processing_stats(),
            "queue": self.get_queue_stats(),
            "cache": self.get_cache_stats(),
            "monitoring_active": self.monitoring
        }
        
    def reset_stats(self):
        """重置统计信息"""
        self.tick_processing_times.clear()
        self.tick_timestamps.clear()
        self.queue_sizes.clear()
        self.cache_hit_rates.clear()
        
        self.total_ticks = 0
        self.total_processing_time = 0
        self.max_processing_time = 0
        self.min_processing_time = float('inf')
        
        logging.info("性能统计已重置")
